<template>
    <div class="app-container">
        <div v-if="!userStore.isMobile" style="margin-bottom: 10px;">
            <el-button type="primary" icon="Search" @click="getList('1')">获取最新数据</el-button>
            <el-tag type="primary" size="large" style="margin-left: 20px;">提示：1.标黄的行表示没有备注编码或未手动关联出库单 2.标绿的行表示清单数量大于出库数量
                3.标红的行表示清单数量小于出库的数量或出库单中有但正式清单没有</el-tag>
        </div>


        <!-- 搜索框 -->
        <el-input :style="{
            width: userStore.isMobile ? '100%' : '400px',
            marginBottom: userStore.isMobile ? '10px' : '15px'
        }" :size="userStore.isMobile ? 'large' : 'default'" v-model="searchKeyword"
            placeholder="支持输入设备名称、型号、备注编码、清单数量、实际出库数量搜索" clearable />


        <el-table :row-class-name="tableRowClassName" height="70vh" :summary-method="getSummaries" border show-summary
            style="padding: 0px;margin: 0px;" v-loading="loading" :data="filteredSaleList"
            @selection-change="handleSelectionChange">
            <el-table-column label="名称" width="220" align="center" prop="name" />
            <el-table-column label="设备型号" width="220" align="center" prop="model" />
            <el-table-column label="备注编码" align="center" show-overflow-tooltip width="220" prop="remarkCode" />
            <el-table-column label="清单数量" align="center" prop="count" />
            <el-table-column label="实际出库数量" show-overflow-tooltip width="120" align="center" prop="saleCount" />
            <el-table-column label="出库单价" show-overflow-tooltip width="120" align="center" prop="price" />
            <el-table-column label="销售总金额" show-overflow-tooltip width="120" align="center" prop="total" />
            <el-table-column v-if="viewCost" label="实际成本(￥)" show-overflow-tooltip width="120" align="center"
                prop="costTotal" />
            <el-table-column v-if="viewCost" label="毛利" show-overflow-tooltip width="120" align="center"
                prop="profit" />

            <!-- <el-table-column label="操作人" align="center" prop="operator" /> -->
            <!-- <el-table-column label="操作" fixed="right" width="120" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                </template>
</el-table-column> -->
        </el-table>
    </div>
</template>

<script setup name="Costing">
import { listCosting, listCompare, getCosting, delCosting, addCosting, updateCosting } from "@/api/project/costing";
import { listSale, getSale, delSale, addSale, updateSale, gjpListSale, gjpAllListSale, viewCostPermisson } from "@/api/project/sale";
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const props = defineProps({
    datas: {
        type: Object, // 指定类型为对象
        required: true, // 是否必填
    },
    column: {
        type: Number, // 指定类型为数字
        default: 3, // 设置默认值为 3
    },
    sizes: {
        default: 'default',
    },
    personList: {
        default: [],
    },
    payList: {
        default: [],
    },
    attachmentList: {
        default: [],
    },
    implementList: {
        default: [],
    },
    warrantyList: {
        default: [],
    },
    accountingList: {
        default: [],
    },


    isView: {
        default: false,
    },


});
const { datas } = toRefs(props);

const { proxy } = getCurrentInstance();

const costingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const saleList = ref([]);
const viewCost = ref(false)
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 1000,
        name: null,
        model: null,
        param: null,
        brand: null,
        count: null,
        unit: null,
        price: null,
        totalPrice: null,
        discountRate: null,
        discountPrice: null,
        remarkCode: null,
        preCount: null,
        prePrice: null,
        preUnit: null,
        finalCount: null,
        finalCost: null,
        loginIp: null,
        loginDate: null,
        projectNo: null,
        goodsId: null,
        refresh: null
    },
    rules: {
        id: [
            { required: true, message: "id不能为空", trigger: "blur" }
        ],
    }
});

const { queryParams, form, rules } = toRefs(data);

const searchKeyword = ref('');

// 计算属性过滤数据
const filteredSaleList = computed(() => {
    const keyword = searchKeyword.value.trim().toLowerCase();
    if (!keyword) {
        return costingList.value;
    }

    return costingList.value.filter(item =>
        [item.remarkCode, item.name, item.modal, item.count, item.saleCount].some(field =>
            field != null && String(field).toLowerCase().includes(keyword)
        )
    );


});

/** 查询正式清单的商品列表 */
function getList(type) {
    loading.value = true;
    queryParams.value.projectNo = datas.value.projectNo
    queryParams.value.refresh = type
    listCompare(queryParams.value).then(response => {
        costingList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
    }).finally(() => {
        loading.value = false;
    });



}


// 行样式方法
const tableRowClassName = ({ row }) => {

    // return 'error-row'

    if (row.status == 1) {
        return 'warning-row'
    }

    if (row.status == 2) {
        return 'success-row'
    }

    if (row.status == 3) {
        return 'error-row'
    }

};


// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        name: null,
        model: null,
        param: null,
        brand: null,
        count: null,
        unit: null,
        price: null,
        totalPrice: null,
        discountRate: null,
        discountPrice: null,
        remarkCode: null,
        preCount: null,
        prePrice: null,
        preUnit: null,
        finalCount: null,
        finalCost: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        loginIp: null,
        loginDate: null,
        projectNo: null
    };
    proxy.resetForm("costingRef");
}


// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加正式清单的商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    let params = {
        housekeeperProject: datas.value.housekeeperProject
    }

    if (!params.housekeeperProject) {
        proxy.$modal.msgError("未关联管家婆项目,请关联");
        loading.value = false;
        return
    }
    console.log("params.housekeeperProject", params.housekeeperProject);

    gjpAllListSale(params).then(response => {
        console.log('所有出库单', response);
        saleList.value = response.data;
    });


    const _id = row.id || ids.value
    getCosting(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "选择实际对应的出库数据";
    });


}



function getSummaries(param) {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = `合计（共 ${data.length} 条）`;
            return;
        }

        const prop = column.property;

        // 需要统计的列配置
        const statsColumns = {
            count: { name: '数量', format: 'int' },
            saleCount: { name: '实际出库数量', format: 'int' },
            total: { name: '销售总金额', format: 'int' },
            costTotal: { name: '实际成本', format: 'int' },
            profit: { name: '毛利', format: 'int' },
        };

        if (statsColumns[prop]) {
            const values = data.map(item => Number(item[prop]));
            if (!values.every(value => isNaN(value))) {
                const sum = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    return isNaN(value) ? prev : prev + value;
                }, 0);

                // 格式化输出
                switch (statsColumns[prop].format) {
                    case 'int':
                        sums[index] = Math.round(sum).toString(); // 四舍五入取整，转为字符串
                        break;
                    case 'money':
                        sums[index] = '￥ ' + sum.toFixed(2); // 四舍五入保留两位小数并添加货币符号
                        break;
                    default:
                        sums[index] = sum.toString();
                }
            } else {
                sums[index] = 'N/A';
            }
        } else {
            sums[index] = '';
        }
    });

    return sums;
}


const setRemarkCode = (id) => {
    if (id == undefined) {
        form.value.remarkCode = '';
        return
    }
    const filteredObjects = saleList.value.find((obj) => obj.goodsId == id);
    form.value.remarkCode = '';
    console.log("filteredObjects", filteredObjects);
    form.value.remarkCode = filteredObjects?.goodsAllName || '';
    console.log("setHousekeeperName", form.value.remarkCode);
}


function getViewCostPermisson() {
    viewCostPermisson(null).then(response => {
        console.log("看成本的权限", response);
        viewCost.value = response
    }).finally(() => {
    });
}

onMounted(() => {
    getViewCostPermisson()
    // nextTick(() => {
    console.log("当前", datas);
    getList("0")
    // })
})
</script>


<style scoped>
.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}


:deep(.el-table .error-row) {
    --el-table-tr-bg-color: #fee2e2;
    /* 浅红色背景 */
    color: #dc2626;
    /* 深红色文字 */
}
</style>



<style>
.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}


:deep(.el-table .error-row) {
    --el-table-tr-bg-color: #fee2e2;
    /* 浅红色背景 */
    color: #dc2626;
    /* 深红色文字 */
}
</style>